<template>
  <div>
    <a-input-search
      v-model="searchKey"
      style="margin-bottom: 8px"
      placeholder="搜索"
    />
    <a-tree
      v-model:expanded-keys="treeExKeys"
      :data="treeData"
      :field-names="{
        key: 'id',
        title: 'classifyName',
      }"
      @select="contractSelect"
    >
      <template #icon="data">
        <icon-folder v-if="!data.isLeaf" />
        <icon-file v-if="data.isLeaf" />
      </template>
      <template #title="nodeData">
        <template v-if="getMatchIndex(nodeData?.classifyName) < 0">{{
          nodeData?.classifyName
        }}</template>
        <span v-else>
          {{
            nodeData?.classifyName?.substr(
              0,
              getMatchIndex(nodeData?.classifyName)
            )
          }}
          <span style="color: red">
            {{
              nodeData?.classifyName?.substr(
                getMatchIndex(nodeData?.classifyName),
                searchKey.length
              )
            }} </span
          >{{
            nodeData?.classifyName?.substr(
              getMatchIndex(nodeData?.classifyName) + searchKey.length
            )
          }}
        </span>
      </template>
    </a-tree>
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed, onMounted } from 'vue';
  import { getTree } from '@/api/purchase-order/purchaseOrderPreparation';

  const originTreeData = ref<any>([]);
  const searchKey = ref('');
  const emit = defineEmits(['selectId', 'selectCode', 'selected']);
  const treeData = computed(() => {
    if (!searchKey.value) {
      return originTreeData.value;
    }
    return searchData(searchKey.value);
  });
  const treeExKeys = ref<any[]>([]);
  function searchData(keyword: string) {
    const loop = (data: any[]) => {
      const result: any[] = [];
      let erpKeys: any[] = [];
      data.forEach((item: any) => {
        if (
          item.classifyName.toLowerCase().indexOf(keyword.toLowerCase()) > -1
        ) {
          result.push({ ...item });
        } else if (item.children) {
          const filterData = loop(item.children);
          if (filterData.length) {
            result.push({
              ...item,
              children: filterData,
            });
            item.children.forEach((res: { id: any }) => {
              erpKeys.push(res.id);
            });
            erpKeys.push(item.id);
          }
        }
      });
      erpKeys = Array.from(new Set(erpKeys));
      treeExKeys.value = erpKeys;
      return result;
    };
    return loop(originTreeData.value);
  }
  const initData = () => {
    getTree({}).then((res: any) => {
      if (res.code === 200) {
        originTreeData.value = res.data;
      }
    });
  };
  onMounted(() => {
    initData();
  });

  const getMatchIndex = (title: string) => {
    if (!searchKey.value) return -1;
    return title.toLowerCase().indexOf(searchKey.value.toLowerCase());
  };
  const contractSelect = (val: any, data: any) => {
    emit('selectId', val);
    emit('selectCode', data.node.classifyCode);
    emit('selected', data.node);
  };
  defineExpose({ initData });
</script>
